import Vue from 'vue'
import debounce from 'lodash.debounce'
import App from './App'
import pageHead from './components/page-head.vue'

import store from './store'

import WGoodsList from './components/w-goods-list.vue'
import FootTab from './components/foot-tab.vue'
import lazyImage from './components/lazy-image.vue'
import mIcon from './components/m-icon/m-icon.vue';
import request from '@/common/request/request.js'
import ajax from '@/common/js/ajax.js'
import wLoading from '@/components/w-loading/w-loading.vue';
import YkHeader from '@/components/yk/yk-header.vue';
import html2canvas from 'html2canvas';
import 'ican-H5Api';


function setupWebViewJavascriptBridge(callback) {
	/* if (window.WebViewJavascriptBridge) {
		return callback(WebViewJavascriptBridge);
	}

	if (uni.getSystemInfoSync().platform === 'android') {
		document.addEventListener('WebViewJavascriptBridgeReady',function() {
			callback(WebViewJavascriptBridge)
		},
			false
		);
	}
	if (window.WVJBCallbacks) {
		return window.WVJBCallbacks.push(callback);
	}

	window.WVJBCallbacks = [callback];
	var WVJBIframe = document.createElement('iframe');
	WVJBIframe.style.display = 'none';
	WVJBIframe.src = 'https://__bridge_loaded__';
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function() {
		document.documentElement.removeChild(WVJBIframe);
	}, 0); */

	
	if (window.WebViewJavascriptBridge) {
		return callback(WebViewJavascriptBridge);
	}
	if (window.WVJBCallbacks) {
		return window.WVJBCallbacks.push(callback);
	}
	document.addEventListener(
		'WebViewJavascriptBridgeReady',
		function() {
			WebViewJavascriptBridge.init(function(message, responseCallback) {
				responseCallback(data);
			});
			callback(WebViewJavascriptBridge)
		},
		false
	);

	window.WVJBCallbacks = [callback];
	var WVJBIframe = document.createElement('iframe');
	WVJBIframe.style.display = 'none';
	WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function() {
		document.documentElement.removeChild(WVJBIframe)
	}, 0);
}

window.UrlParam = function() {
	var name, value;
	var str = location.href; //取得整个地址栏
	var num = str.indexOf("?")

	str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

	var arr = str.split("&"); //各个参数放到数组里
	const param = {};
	for (var i = 0; i < arr.length; i++) {
		num = arr[i].indexOf("=");
		if (num > 0) {
			name = arr[i].substring(0, num);
			value = arr[i].substr(num + 1);
			param[name] = value;
		}
	}
	return param
};

window.savePicCommon = function() {
	const dom = document.querySelector('imgArea');
	// 创建一个新的canvas
	const Canvas = document.createElement('canvas');
	const width = document.body.offsetWidth; // 可见屏幕的宽
	const height = document.body.offsetHeight; // 可见屏幕的高
	const scale = window.devicePixelRadio; // 设备的devicePixelRadio
	// 将Canvas画布放大scale倍，然后放在小的屏幕里，解决模糊问题
	Canvas.width = width * scale;
	Canvas.height = height * scale;
	Canvas.getContext('2d').scale(scale, scale);
	html2canvas(dom, {
		canvas: Canvas,
		scale,
		useCORS: true,
		logging: true,
		width: width + 'px',
		hegiht: height + 'px',
	}).then((canvas) => {
		const context = canvas.getContext('2d');
		// 关闭抗锯齿形
		context.mozImageSmoothingEnabled = false;
		context.webkitImageSmoothingEnabled = false;
		context.msImageSmoothingEnabled = false;
		context.imageSmoothingEnabled = false;
		// canvas转化为图片
		canvas2Image(canvas, canvas.width, canvas.height);
	});
};

window.genCommonData = function() {
	let url = window.location.href;
	let reg_url = /^[^\?]+\?([\w\W]+)$/,
		reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
		arr_url = reg_url.exec(url),
		ret = {};
	if (arr_url && arr_url[1]) {
		let str_para = arr_url[1],
			result;
		while ((result = reg_para.exec(str_para)) != null) {
			ret[result[1]] = result[2];
		}
	}
	let token = ret.token;
	if (token != '' && token != 'null' && token != null && token != undefined && token != 'undefined') {
		uni.setStorageSync('token', decodeURI(token));
		uni.setStorageSync('bump', ret.bump);
		uni.setStorageSync('relationId', ret.relationId);
		uni.setStorageSync('mobile', ret.customerId);
		switch (uni.getSystemInfoSync().platform) {
			case 'android':
				uni.setStorageSync('anAppVersion', ret.appVersion);
				break;
			case 'ios':
				uni.setStorageSync('iosAppVersion', ret.appVersion);
				break;
			default:
				break;
		}
	}
};

window.callNative = function(name, param, callback, h5Call) {
	const isAndroid = uni.getSystemInfoSync().platform === 'android';
	if (isAndroid || uni.getSystemInfoSync().platform === 'ios') {
		/* if (isAndroid) {
			try {
				const args = Object.values(param);
				return appData[name](...args);
			} catch (e) {
				console.log(e)
			}
		} */
		setupWebViewJavascriptBridge(function(bridge) {
			bridge.callHandler(name, param, callback)
		})
	} else {
		h5Call && h5Call(param);
	}
}
window.registerNative = function(name, callback) {
	setupWebViewJavascriptBridge(function(bridge) {
		bridge.registerHandler(name, callback)

		setTimeout(function() {
			callback('response data get sucess');
		}, 0)
	})
}

window.routerHistory = [window.location.hash];
window.headHeightSet = function() {
	const head = document.querySelector('.status-bar.fixed');
	if (head) {
		const headHeight = head.offsetHeight;
		document.querySelector('.page-head').style.height = headHeight + 'px';
	}
};
window.appNavigateTo = function(aUrl) {
	if (this.$userBrowser === 'wx') {
		window.open(aUrl);
	} else {
		callNative('onWebView', {
			webUrl: aUrl
		}, '', function(param) {
			window.open(param.webUrl)
		});
	}
}.bind(Vue);
window.h5NavigateTo = function(aUrl, hUrl) {
	const url = hUrl || aUrl.url;
	window.routerHistory.push(url);
	console.log(url);
	uni.navigateTo({
		url: url
	});
};
window.h5RedirectTo = function(aUrl, hUrl) {
	const url = hUrl || aUrl.url;
	window.routerHistory[window.routerHistory.length - 1] = url;
	uni.redirectTo({
		url: url
	});
};
window.h5NavigateBack = function() {
	if (window.routerHistory.length > 1) {
		window.routerHistory.pop();
		uni.navigateBack();
	} else {
		callNative('navigateBack')
	}
};

window.version = 0;

window.genVersion = function() {
	switch (uni.getSystemInfoSync().platform) {
		case 'android':
			break;
		case 'ios':
			let iosVersion = uni.getStorageSync('iosAppVersion');
			if (iosVersion == '2.2.1') {
				window.version = 1;
			} else {
				window.version = 0;
			}
			break;
		default:
			window.version = 1;
			break;
	}
}

window.genAppData = function() {
	callNative('getWebcommonParams', '', (data) => {
		let datas = data;
		let token = datas.token;
		if (token != '' && token != 'null' && token != null && token != undefined && token != 'undefined') {
			uni.setStorageSync('token', decodeURI(datas.token));
			uni.setStorageSync('bump', datas.bump);
			uni.setStorageSync('relationId', datas.relationId);
			uni.setStorageSync('mobile', datas.customerId);
			switch (uni.getSystemInfoSync().platform) {
				case 'android':
					uni.setStorageSync('anAppVersion', datas.appVersion);
					break;
				case 'ios':
					uni.setStorageSync('iosAppVersion', datas.appVersion);
					break;
				default:
					break;
			}
		}
		console.log("token===" + decodeURI(data.token))
		console.log("appVersion===" + data.appVersion)
	});
}

window.onStartLogin = () => callNative('onStartLogin', '', '', () => {
	h5NavigateTo({
		url: '../login/login'
	});
});

window.onSavePhoto = function(url) {
	callNative('savePic', url, '', '');
};

window.onEvent = function(name) {
	callNative('onEvent', name, '', '');
};
/**
 * @param {Object} jumpUrl   跳转的URL
 * @param {Object} title     文字标题
 * @param {Object} drawableUrl   图片URL
 * @param {Object} description   描述
 */
window.onShare = function(jumpUrl, title, drawableUrl, description) {
	let data = {
		jumpUrl: jumpUrl,
		title: title,
		drawableUrl: drawableUrl,
		description: description
	}
	callNative('onShare', data, '', '');
};

window.h5ReLaunch = function(url) {
	window.routerHistory = [url];
	console.log('reLaunch url ===' + url);
	uni.reLaunch({
		url
	})
};

registerNative('h5ReLaunch', function(data) {
	let url = data;
	console.log('gen app h5ReLaunch data==' + data);
	url = data.substr(data.indexOf('#') + 1);
	h5ReLaunch(url);
});

const fontSizeSet = () => {
	document.documentElement.style.fontSize = (10 * document.body.clientWidth / 75).toFixed(2) + 'px';
};
const windowResize = function() {
	console.log('resize')
	fontSizeSet();
	headHeightSet();
};

windowResize();
window.onresize = debounce(windowResize, 200);
Vue.config.productionTip = false;

Vue.prototype.$store = store;
let url = 'https://bncf2api.sqqmall.com';
// let userUrl = 'https://bncf2api.sqqmall.com';
let userUrl = 'https://bncf2api.sqqmall.com';
// http://order-test04.sqqmall.com

let webUrl = 'https://bncf3h5.sqqmall.com/#/';

//只有以 VUE_APP_ 开头的变量会被 webpack.DefinePlugin 静态嵌入到客户端侧的包中。
if (process.env.VUE_APP_API === "development") {
	url = 'https://order-test04.sqqmall.com';
	userUrl = 'https://order-test04.sqqmall.com';
	webUrl = 'https://b2h5.sqqmall.com/#/';
} else if (process.env.VUE_APP_API === "ios") {
	url = 'https://ac.sqqmall.com';
	userUrl = 'https://ac.sqqmall.com';
	webUrl = 'https://b2h5-test.sqqmall.com/#/';
} else if (process.env.VUE_APP_API === "qa") {
	url = 'https://b2api-test.sqqmall.com';
	userUrl = 'https://b2api-test.sqqmall.com';
	webUrl = 'https://b2h5-test.sqqmall.com/#/';
}

window.getToken = function() {
	let token = '';
	callNative('getToken', '', (data) => {
		token = data;
		uni.setStorageSync('token', data);
	});
}


Vue.prototype.$usereq = userUrl;
Vue.prototype.$userBrowser = '';
Vue.prototype.$serverUrl = url;
Vue.prototype.$httpUrl = webUrl;
Vue.prototype.$redirect_uri = webUrl;
window.toH5Url = url;

Vue.component('w-goods-list', WGoodsList)
Vue.component('foot-tab', FootTab)
Vue.component('lazy-image', lazyImage)
Vue.component('page-head', pageHead)
Vue.component('mIcon', mIcon)
Vue.component('w-loading', wLoading);
Vue.component('yk-header', YkHeader);
// 全局配置
request.setConfig({
	baseUrl: url, // 此为测试地址，需加入到域名白名单，或者更改为您自己的线上地址即可
	// baseUrl:'/dpc/coupon-product',
	/* dataType: 'json', // 可删除，默认为json
	contentType: "application/json",
	responseType: 'text', // 可删除，默认为text */
	// 设置请求头，支持所有请求头设置，也可不设置，去掉header就行
	header: {
		'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
		'content-type': 'application/json'
	}
})

// 设置请求拦截器
request.interceptors.request(config => {
	try {
		// 配置参数和全局配置相同，此优先级最高，会覆盖在其他地方的相同配置参数

		// 追加请求头，推荐
		config.header['content-type'] = 'application/json';
		// config.header.blade-auth = uni.getStorageSync('token');
		// 覆盖请求头
		/* config.header = {
		    'blade-auth': uni.getStorageSync('token'),
		    'content-type': 'application/json'
		} */
		/* uni.showLoading({
		    title: 'loading...',
		    mask: true
		}); */
		// return false; // 终止请求
		return config; // 返回修改后的配置，如未修改也需添加这行
	} catch (e) {
		uni.hideLoading();
	}
})

// 设置响应拦截器
request.interceptors.response(res => {
	try {
		uni.hideLoading();
		return res; // 原样返回
	} catch (e) {
		uni.hideLoading();
		console.log("error====" + e.message)
	}
})


// // 挂载到全局vue实例上，在页面中可以使用this.$request调用request实例下相应方法
Vue.prototype.$request = request;
Vue.prototype.$ajax = ajax;


App.mpType = 'app';

// function mountApp() {
const app = new Vue({
	store,
	...App
})
app.$mount()
// }

window.statusBarHeight = 20

window.getStatusBarHeight = function() {
	callNative('getStatusBarHeight', '', function(response) {
		window.statusBarHeight = response;
		console.log('getStatusBarHeight==' + response);
	});
}

/*callNative('getStatusBarHeight', '', function(response) {
	window.statusBarHeight = response;
	console.log('getStatusBarHeight==' + response);
	mountApp()
}, mountApp); */
